package com.sharkburner.security.service;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import com.sharkburner.aeris.bean.UserBean;
import com.sharkburner.aeris.service.user.UserService;

@Component
public class WSAuthenticationProvider implements AuthenticationProvider {
	// TODO: To refact
	@Autowired
	private UserService userService;
	private String userName;
	private String password;
	private String group;

	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {

		UsernamePasswordAuthenticationToken result = null;

		userName = authentication.getPrincipal().toString();
		password = authentication.getCredentials().toString();
		UserBean userBean = userService.find(userName, password);

		if (userBean != null) {
			boolean sameUser = userName.equals(authentication.getPrincipal());
			boolean samePwd = password.equals(authentication.getCredentials());
			group = userBean.getGroupName();

			if (sameUser && samePwd) {
				Collection<GrantedAuthority> auth = new ArrayList<GrantedAuthority>();
				auth.add(new SimpleGrantedAuthority(group));
				result = new UsernamePasswordAuthenticationToken(userName,
						password, auth);

			} else {
				throw new BadCredentialsException("Error message!");
			}
		}

		return result;
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return UsernamePasswordAuthenticationToken.class
				.isAssignableFrom(authentication);
	}

}
